<template>
  <div class="article-container">
    <!--数据表格-->
    <el-row>
      <el-col :span="22" :offset="1">
        <!--卡片-->
        <card class="table-container" cardName="用户列表" :scalable="false">
          <!--工具栏-->
          <tool-bar slot="tool" @emptyQuery="emptyQuery"  @receiveKeyword="receiveKeyword">
            <div slot="buttonContainer" class="button-all-container">
              <!--工具栏上第一个按钮-->
              <div class="btn-container" v-if="hasPermission('user:insert')">
                <el-button class="toolbar-button" @click="showSaveUserModal">
                  <i class="el-icon-circle-plus-outline"></i>
                  新增用户
                </el-button>
              </div>
              <!--工具栏上第二个按钮-->
              <div class="btn-container" v-if="hasPermission('user:delete')">
                <el-button class="toolbar-button" @click="batchDelete">
                  <i class="iconfont icon-shanchu"></i>
                  批量删除
                </el-button>
              </div>
            </div>
          </tool-bar>
          <!--表格-->
          <el-table
            slot="content"
            :data="userData"
            stripe
            border
            :fit="true"
            style="width: 100%"
            @select="selectUser"
            @select-all="selectUser"
            :key="tableKey">
            <el-table-column
              type="selection"
              :selectable="isNotRoot"
              min-width="55"
              align="center">
            </el-table-column>
            <el-table-column
              prop="username"
              label="用户名"
              min-width="60">
            </el-table-column>
            <el-table-column
              prop="nickname"
              label="昵称"
              min-width="60">
            </el-table-column>
            <el-table-column
              prop="mobile"
              label="手机号码"
              min-width="60">
            </el-table-column>
            <el-table-column
              align="center"
              prop="roleName"
              label="角色"
              min-width="50">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.roleName | showTagColor"
                  disable-transitions>
                  {{scope.row.roleName}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="loginCount"
              label="登录次数"
              min-width="40">
              <template slot-scope="scope">
                <span>{{scope.row.roleName == '访客'? '-': scope.row.loginCount}}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="usable"
              label="启用"
              min-width="40">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.usable"
                  :disabled="!hasPermission('user:update')"
                  active-color="#409EFF"
                  :active-value="1"
                  :inactive-value="0"
                  v-if="isNotRoot(scope.row)"
                  @change="changeUsable(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              min-width="80">
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="140">
              <template slot-scope="scope">
                <span v-if="!hasPermission('user:update') && !hasPermission('user:resetPassword')
                  && !hasPermission('user:assignRole') && !hasPermission('user:delete')">-</span>
                <el-button
                  type="primary"
                  class="editBtn"
                  size="small"
                  v-if="hasPermission('user:update')"
                  :disabled="!isNotRoot(scope.row)"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  type="warning"
                  size="small"
                  v-if="hasPermission('user:resetPassword')"
                  :disabled="!isNotRoot(scope.row)"
                  @click="handleResetPassword(scope.$index, scope.row)">密码重置</el-button>
                <el-button
                  type="info"
                  size="small"
                  v-if="hasPermission('user:assignRole')"
                  :disabled="!isNotRoot(scope.row)"
                  @click="handleAssignRole(scope.$index, scope.row)">分配角色</el-button>
                <el-button
                  size="small"
                  type="danger"
                  v-if="hasPermission('user:delete')"
                  :disabled="scope.row.username == 'root'? true: false"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </card>
      </el-col>
    </el-row>
    <!--分页插件-->
    <pagination @getCurrentPage="getCurrentPageFromPagination" :total="total"></pagination>

    <save-user-template
      :userDataFromParent="handleCurrentDataForSave"
      @reloadTable="loadDataForUser"
      ref="saveUserTemplate"></save-user-template>
    <reset-password-template
      :userDataFromParent="handleCurrentDataForReset"
      @reloadTable="loadDataForUser"
      ref="resetPasswordTemplate"></reset-password-template>
    <assign-role-template
      :userDataFromParent="handleCurrentDataForAssign"
      @reloadTable="loadDataForUser"
      ref="assignRoleTemplate"></assign-role-template>
  </div>
</template>

<script>
  import Card from 'components/common/card/Card';
  import Pagination from 'components/common/pagination/Pagination';
  import ToolBar from 'components/content/toolbar/ToolBar';

  import ResetPasswordTemplate from 'views/userView/subView/ResetPasswordTemplate';
  import SaveUserTemplate from 'views/userView/subView/SaveUserTemplate';
  import AssignRoleTemplate from 'views/userView/subView/AssignRoleTemplate';

  import {getUserByPage, changeUsable, deleteByIds} from "../../network/viewsRequest/user";
  import {hasPermission} from "../../common/permission";

  export default {
    name: 'UserView',
    data() {
      return {
        query: { // 查询条件都放这里边
          keyword: '',
          currentPage: 1, // 当前页
          pageSize: 10, // 一页显示几条数据
        },
        userData: [],
        multiSelections: [], // 多选的集合
        total: 0, // 总数据量
        handleCurrentDataForSave: {}, // 传递给保存模态框需要模态框操作的数据
        handleCurrentDataForReset: {}, // 传递给重置模态框需要模态框操作的数据
        handleCurrentDataForAssign: {}, // 传递给分配模态框需要模态框操作的数据
      }
    },
    methods: {
      hasPermission(permission) {
        return hasPermission(permission);
      },
      /**
       * 获取表格中用户的数据
       */
      loadDataForUser() {
        getUserByPage(this.query).then(res => {
          if (res.code == 1) {
            this.userData = res.data.items;
            this.total = res.data.total;
          } else {
            this.userData = [];
            this.total = 0;
          }

        });
      },
      /**
       * 清空查询条件
       */
      emptyQuery() {
        let currentPage = this.query.currentPage;
        let pageSize = this.query.pageSize;
        this.query = {
          keyword: '',
          currentPage: currentPage,
          pageSize: pageSize,
        }
        this.loadDataForUser();
      },
      /**
       * 接受子组件中关键字
       */
      receiveKeyword(keyword) {
        this.query.keyword = keyword;
        this.query.currentPage = 1;
        this.loadDataForUser();
      },
      /**
       * 用户点击分页上的页码触发的事件
       */
      getCurrentPageFromPagination() {
        this.query.currentPage = page;
        this.loadDataForUser();
      },
      /**
       * 修改用户的启用状态
       */
      changeUsable(row) {
        changeUsable(row.id, row.usable).then(res => {
          if (res.code == 1) {
            this.$message.success("更新成功");
          } else {
            this.$message.error(res.message);
          }
          this.loadDataForUser();
        })
      },
      /**
       * 点击多选框时调用的方法
       * @param selection 已经选中的集合，
       * @param row 当前选中的行
       */
      selectUser(selection, row) {
        this.multiSelections = selection;
      },
      /**
       * 点击新增用户时打开的新增用户模态框
       */
      showSaveUserModal() {
        this.handleCurrentDataForSave = {};
        this.$refs.saveUserTemplate.show();
      },
      /**
       * 用户点击重置密码调用的方法
       * @param index 当前这行数据的索引
       * @param row 当前操作这行数据的内容
       */
      handleResetPassword(index, row) {
        this.handleCurrentDataForReset = row;
        this.$refs.resetPasswordTemplate.show();
      },
      /**
       * 用户点击分配角色调用的方法
       * @param index 当前这行数据的索引
       * @param row 当前操作这行数据的内容
       */
      handleAssignRole(index, row) {
        this.handleCurrentDataForAssign = row;
        this.$refs.assignRoleTemplate.show();
      },
      /**
       * 用户点击编辑用户信息调用的方法
       * @param index 当前这行数据的索引
       * @param row 当前操作这行数据的内容
       */
      handleEdit(index, row) {
        // 1.回显数据
        this.handleCurrentDataForSave = row;
        // 2.打开保存模态框
        this.$refs.saveUserTemplate.show();
      },
      /**
       * 用户点击删除用户调用的方法
       * @param index 当前这行数据的索引
       * @param row 当前操作这行数据的内容
       */
      handleDelete(index, row) {
        let delIds = [row.id];
        this.deleteLogic(delIds);
      },
      /**
       * 批量删除用户
       */
      batchDelete() {
        if (this.multiSelections.length == 0) {
          this.$message.error("请选择需要进行删除的用户信息");
          return;
        }
        let delIds = this.multiSelections.map(item => {
          return item.id;
        });
        this.deleteLogic(delIds);
      },
      /**
       * 删除代码的逻辑
       * @param ids 删除的集合
       */
      deleteLogic(ids) {
        this.$confirm("确定要进行删除吗？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          deleteByIds(ids.join()).then(res => {
            if (res.code == 1) {
              this.$message.success("删除成功！");
              this.loadDataForUser();
            } else {
              this.$message.error(res.message);
            }
          })
        }).catch(() => {
          this.$message.info("删除操作已经被取消");
        })

      },
      /**
       * 本方法是用来判断某行对应的数据是否是root用户的，如果是，返回false，即该行不能被选中；反之返回true，即该行能被选中
       * @param row 行数据
       * @param index 行索引
       * @returns {boolean} 如果是，返回false，即该行不能被选中；反之返回true，即该行能被选中
       */
      isNotRoot(row, index) {
        if (row.username == 'root') {
          return false;
        } else {
          return true;
        }
      }
    },
    filters: {
      showTagColor(roleName) {
        if (roleName == '超级管理员') {
          return 'danger'
        } else if (roleName == '普通管理员') {
          return 'primary'
        } else {
          return 'info'
        }
      }
    },
    mounted() {
      this.loadDataForUser();
    },
    computed: {
      tableKey() {
        let key = '';
        for (let i = 0; i < this.userData.length; i++) {
          key += this.userData[i].updateTime;
        }
        return key;
      }
    },
    components: {
      Card,
      Pagination,
      ToolBar,
      ResetPasswordTemplate,
      SaveUserTemplate,
      AssignRoleTemplate
    }
  }
</script>

<style scoped>

  .toolbar-button {
    width: 120px;
    height: 36px;
    padding: 0 20px 0 15px;
    vertical-align: middle;
  }
  .table-container {
    width: 100%;
    height: 100%;
    position: relative;
    display: inline-block !important;
    vertical-align: bottom;
    position: relative;
  }
  .button-all-container {
    display: inline-block;
    vertical-align: bottom;
  }

  .custom-container {
    display: inline-block;
    margin-left: 10px
  }

  .el-card {
    margin-top: 30px;
  }

  .el-select {
    width: 110px;
  }
  .btn-container {
    margin-right: 5px;
  }

  .category-select {
    margin-right: 5px;
  }

</style>

<style>

  .el-button--default:first-child i,
  .el-button--default:last-child i {
    font-size: 12px;
  }

  .el-button--default span {
    font-size: 14px !important;
  }

  .el-table__body td {
    padding-top: 10px !important;
    padding-bottom: 10px !important;
  }

  .el-input--small .el-input__inner {
    height: 36px;
  }

  .el-select-dropdown__wrap, .el-scrollbar__wrap {
    margin-bottom: 0px !important
  }

  .el-button {
    margin-left: 0px !important;
    margin-right: 10px;
  }
</style>
